<template>
  <a-modal centered v-model="visible" title="退件预报" width="50%">
    <template slot="footer">
      <a-button
        style="background: #d7d7d7; color: #fff; border: none"
        @click="
          () => {
            this.visible = false;
          }
        "
        >取消</a-button
      >

      <!-- <a-button
        style="background: #d7d7d7; color: #fff; border: none"
        @click="
          () => {
            this.visible = false;
          }
        "
        v-if="modalFlag === 'systemEdit' && tabKey != '76'"
        >取消</a-button
      > -->
      <a-button
        v-if="
          modalFlag === 'editcClientSide' && tabKey != '86' && tabKey != '106'
        "
        :loading="loading"
        type="primary"
        @click="handleOk(tabKey)"
        >确认</a-button
      >
      <a-button
        v-if="modalFlag === 'add'"
        :loading="loading"
        type="primary"
        @click="handleOk(tabKey)"
        >确认</a-button
      >

      <a-button
        :loading="NoLoading"
        style="background: #f00; color: #fff; border: none"
        @click="isCheck('96')"
        v-if="modalFlag === 'systemEdit' && tabKey === '76'"
        >审核不通过</a-button
      >
      <a-button
        v-if="modalFlag === 'systemEdit' && tabKey === '76'"
        :loading="loading"
        type="primary"
        @click="isCheck('86')"
        >审核通过</a-button
      >
    </template>
    <h3>退件信息</h3>
    <div>
      <a-form-model layout="inline" :model="dto" :rules="rules" ref="fromDto">
        <a-form-model-item label="退件标题:" prop="title">
          <a-input :maxLength="128" v-if="inputShow != 'info'" v-model="dto.title"> </a-input>
          <span v-if="inputShow === 'info'">
            {{ dto.title }}
          </span>
        </a-form-model-item>
        <a-form-model-item label="退至仓库:" prop="warehousingId">
          <a-select
            v-if="inputShow != 'info'"
            v-model="dto.warehousingId"
            show-search
            option-filter-prop="children"
            style="width: 200px"
            :filter-option="filterOption"
            @change="(value, option) => changeWarehousing(option)"
          >
            <a-select-option
              :value="item.warehouseId"
              v-for="item in warehouse"
              :key="item.warehouseId"
              :warehousingName="item.titleName"
            >
              {{ item.titleName }}
            </a-select-option>
          </a-select>
          <span v-if="inputShow === 'info'">
            {{ dto.warehousingName }}
          </span>
        </a-form-model-item>
        <a-form-model-item label="退件处理:" prop="typeId">
          <a-select
            v-if="inputShow != 'info'"
            v-model="dto.typeId"
            show-search
            option-filter-prop="children"
            style="width: 200px"
            :filter-option="filterOption"
            @change="(value, option) => changeTypeId(option)"
          >
            <a-select-option
              :value="item.key"
              v-for="item in treatmentArray"
              :key="item.key"
              :titles="item.title"
            >
              {{ item.title }}
            </a-select-option>
          </a-select>
          <span v-if="inputShow === 'info'">
            {{ dto.typeName }}
          </span>
        </a-form-model-item>
        <a-form-model-item label="到仓时间:" prop="scheduledTime">
          <a-date-picker
            :allowClear="false"
            :value="
              dto.scheduledTime === undefined || dto.scheduledTime === null
                ? null
                : moment(dto.scheduledTime, 'YYYY-MM-DD')
            "
            v-if="inputShow != 'info'"
            @change="onChangeScheduledTime"
          />
          <span v-if="inputShow === 'info'">
            {{ dto.scheduledTime }}
          </span>
        </a-form-model-item>
      </a-form-model>
    </div>
    <h3 style="margin-top: 10px">退件预报</h3>
    <p style="display: flex; line-height: 30px" v-if="inputShow != 'info'">
      <a-button
        class="blueBtn"
        type="primary"
        style="margin-left: 20px"
        @click="addBox"
      >
        增加预报SKU
      </a-button>
    </p>
    <!-- 表格 -->
    <a-table
      size="small"
      bordered
      :data-source="dto.logisticsInfos"
      :pagination="false"
    >
      <!-- sku信息 -->
      <a-table-column
        key="byRetreatProductInfos"
        class="columns-tab"
        data-index="byRetreatProductInfos"
        align="center"
        width="70%"
      >
        <div slot="title" class="columns">
          <div style="width: 20%">
            <span style="color: red">*</span>商品名称
          </div>
          <div style="width: 20%"><span style="color: red">*</span>退件SKU</div>
          <div style="width: 20%"><span style="color: red">*</span>数量</div>
          <div style="width: 20%">FNSKU</div>
          <div style="border: none; width: 20%"></div>
        </div>
        <!-- 表格 -->
        <template slot-scope="text, record">
          <ul
            class="pto-list"
            v-for="(item, i) in record.byRetreatProductInfos"
            :key="item.key"
          >
            <li style="width: 20%">
              {{ item.skuName }}
            </li>
            <li
              style="width: 20%"
              :style="
                item.skuId === null || item.skuId === ''
                  ? 'border: 1px solid #f00;border-radius:5px'
                  : 'border: 1px solid #ccc;border-radius:5px'
              "
            >
              <a-select
                v-if="inputShow != 'info'"
                style="width: 100%"
                v-model="item.sku"
                size="small"
                show-search
                option-filter-prop="children"
                :filter-option="filterOption"
                @change="(value, option) => changeSku(option, item, record)"
                placeholder="请选择SKU"
              >
                <a-select-option
                  :value="v.id"
                  v-for="v in RetreatStockArray"
                  :key="v.id"
                  :sku="v.sku"
                  :name="v.skuName"
                  :skuId="v.skuId"
                  :productTag="v.productTag"
                >
                  {{ v.sku }}
                </a-select-option>
              </a-select>
              <span v-if="inputShow === 'info'">
                {{ item.sku }}
              </span>
            </li>
            <li
              style="width: 20%"
              :style="
                item.productNumber === null || item.productNumber === ''
                  ? 'border: 1px solid #f00;border-radius:5px'
                  : 'border: 1px solid #ccc;border-radius:5px'
              "
            >
              <a-input-number
                v-if="inputShow != 'info'"
                style="width: 100%"
                @change="
                  item.productNumber === null
                    ? (item.productNumber = 1)
                    : item.productNumber
                "
                v-model="item.productNumber"
                size="small"
                :min="1"
                :max="100000"
                :default-value="1"
              />
              <span v-if="inputShow === 'info'">
                {{ item.productNumber }}
              </span>
            </li>
            <li style="width: 20%">
              <a-input
              :maxLength="128"
                v-model="item.fnsku"
                size="small"
                v-if="inputShow != 'info'"
              />
              <span v-if="inputShow === 'info'">
                {{ item.fnsku }}
              </span>
            </li>
            <li
              style="border: none; width: 20%"
              class="row-btn"
              v-if="inputShow != 'info'"
            >
              <a-icon
                v-if="
                  record.byRetreatProductInfos.length === 1 ||
                  record.byRetreatProductInfos.length - 1 === i
                "
                style="color: #3eae7c"
                type="plus-circle"
                theme="filled"
                @click="addSku(record)"
              />
              <a-icon
                type="minus-circle"
                style="color: #b4b4b4"
                theme="filled"
                @click="delSku(record, item)"
              />
            </li>
          </ul>
        </template>
      </a-table-column>
      <!-- 装箱数量 -->
      <a-table-column
        key="packingNumber"
        data-index="packingNumber"
        align="center"
        width="15%"
      >
        <span slot="title"> 箱数</span>
        <template slot-scope="text, record">
          <span v-if="inputShow === 'info'">
            {{ record.packingNumber }}
          </span>
          <a-input
          :maxLength="128"
            v-if="inputShow != 'info'"
            @keyup="
              () => {
                if (record.packingNumber) {
                  record.packingNumber = record.packingNumber.replace(
                    /[^\d\.]/g,
                    ''
                  );
                }
              }
            "
            size="small"
            style="width: 100%"
            v-model="record.packingNumber"
          />
        </template>
      </a-table-column>
      <!-- 操作 -->
      <a-table-column
        v-if="inputShow != 'info'"
        key="operation"
        data-index="operation"
        title="操作"
        width="55px"
        align="center"
      >
        <template slot-scope="text, record">
          <a-popconfirm
            title="确定删除吗?"
            okText="确定"
            cancelText="取消"
            @confirm="() => onDelete(record, record.key)"
          >
            <a
              href="javascript:;"
              style="
                color: rgb(243, 56, 29);
                border-bottom: 1px solid rgb(243, 56, 29);
              "
              >删除</a
            >
          </a-popconfirm>
        </template>
      </a-table-column>
    </a-table>

    <h3 style="margin-top: 20px">备注信息：</h3>
    <div class="remark">
      <a-textarea
      :maxLength="256"
        placeholder="期望货物处理时效、货物总体积"
        :rows="2"
        v-if="inputShow != 'info'"
        v-model="dto.remark"
      />
      <span v-if="inputShow === 'info'">
        {{ dto.remark === null || dto.remark === "" ? "暂无" : dto.remark }}
      </span>
    </div>
  </a-modal>
</template>

<script>
import moment from "moment";
import { treeTagDictionary, warehouse_select } from "@/apis/common";
import {
  getRetreatStock,
  by_retreatApply,
  by_retreatApply_edit,
  by_retreatApply_forecast,
  by_retreatApply_through,
} from "@/apis/clientSide/ReturnsList/ReturnsList";
export default {
  props: ["warehouse", "getTableList", "getCountList", "tabKey"],
  created() {
    this.getSelection();
  },

  data() {
    return {
      moment,
      //是否可编辑标杆
      inputShow: "",
      //模态框显示标杆
      modalFlag: "",
      passFlag: true,
      // 退件SKU数组
      RetreatStockArray: [],
      // 处理方式数组
      treatmentArray: [],
      checkFlag: false,
      //库位数据
      storageLocation: [],
      //模态框显示
      visible: false,
      //模态框标杆
      NoLoading: false,
      loading: false,
      rules: {
        title: [
          {
            required: true,
            message: "退件标题必填!",
            trigger: "blur",
          },
        ],
        warehousingId: [
          {
            required: true,
            message: "入库仓库必选!",
            trigger: "blur",
          },
        ],
        typeId: [
          {
            required: true,
            message: "退件处理类型必选!",
            trigger: "blur",
          },
        ],
        scheduledTime: [
          {
            required: true,
            message: "预计到仓时间必填!",
            trigger: "change",
          },
        ],
      },
      //表格数据
      dto: {
        logisticsInfos: [],
        remark: null,
        title: null,
        typeId: null,
        typeName: null,
        warehousingId: null,
        warehousingName: null,
        scheduledTime: null,
      },
      styleBack: {
        border: "1px solid #f00",
        borderRadius: "5px",
      },
      styleYes: {
        border: "1px solid #ccc",
        borderRadius: "5px",
      },
    };
  },
  mounted() {
    this.$bus.$off("PreEntryModal");
    this.$bus.$on("PreEntryModal", (data, flag, show) => {
      if (this.$refs.fromDto) {
        this.$refs.fromDto.resetFields();
      }
      data.logisticsInfos.forEach((item) => {
        item.key = item.id;
      });
      this.visible = true;
      this.dto = { ...data };
      this.modalFlag = flag;
      this.getStorageLocation();
      this.inputShow = show;
    });
  },
  methods: {
    //预计到仓时间
    onChangeScheduledTime(date, dateString) {
      this.dto.scheduledTime = dateString;
    },
    //   /管理端审核按钮
    isCheck(flag) {
      if (flag === "86") {
        this.loading = true;
        setTimeout(async () => {
          let { code } = await by_retreatApply_forecast(this.dto.id, flag);
          if (code === "10000") {
            this.loading = false;
            this.getTableList();
            this.getCountList();
            this.visible = false;
          }
        }, 1000);
      } else if (flag === "96") {
        this.NoLoading = true;
        setTimeout(async () => {
          let { code } = await by_retreatApply_forecast(this.dto.id, flag);
          if (code === "10000") {
            this.v = false;
            this.getTableList();
            this.getCountList();
            this.visible = false;
          }
        }, 1000);
      }
    },
    //物流方式改变
    changeWarehousing(option) {
      this.dto.warehousingName = option.data.attrs.warehousingName;
    },
    //退件处理改变
    changeTypeId(option) {
      this.dto.typeName = option.data.attrs.titles;
    },
    //SKU改变
    changeSku(option, item, record) {
      let flag = true;
      record.byRetreatProductInfos.forEach((v) => {
        if (option.data.attrs.sku === v.sku) {
          flag = false;
          item.skuName = "请选择SKU";
          this.$message.error("同一箱子只能不能添加多个同名SKU！");
        }
      });
      if (flag) {
        item.skuName = option.data.attrs.name;
        item.skuId = option.data.attrs.skuId;
        item.sku = option.data.attrs.sku;
        item.productTag = option.data.attrs.productTag;
      }
    },
    //模态框确定
    handleOk(tabKey) {
      this.loading = true;
      this.passFlag = true;
      this.$refs.fromDto.validate((valid) => {
        if (valid) {
          if (this.dto.logisticsInfos.length === 0) {
            this.$message.error("请新增箱子！");
            this.loading = false;
            return false;
          }
          this.dto.logisticsInfos.forEach((item) => {
            item.byRetreatProductInfos.forEach((v) => {
              if ((v.skuId ?? "") == "" || (v.productNumber ?? "") == "") {
                this.passFlag = false;
                return false;
              }
            });
          });
          if (this.passFlag) {
            this.dto.retreatType = 1;
            if (this.modalFlag === "add") {
              setTimeout(async () => {
                let { code } = await by_retreatApply(this.dto);
                if (code === "10000") {
                  this.loading = false;
                  this.visible = false;
                  this.getTableList();
                  this.getCountList();
                }
              }, 1000);
            } else if (this.modalFlag === "editcClientSide") {
              if (tabKey === "76") {
                setTimeout(async () => {
                  let { code } = await by_retreatApply_edit(this.dto);
                  if (code === "10000") {
                    this.loading = false;
                    this.visible = false;
                    this.getTableList();
                    this.getCountList();
                  }
                }, 1000);
              } else if (tabKey === "96") {
                setTimeout(async () => {
                  let { code } = await by_retreatApply_through("76", this.dto);
                  if (code === "10000") {
                    this.loading = false;
                    this.visible = false;
                    this.getTableList();
                    this.getCountList();
                  }
                }, 1000);
              }
            }
          } else {
            this.loading = false;
            this.$message.error("请检查必填项!");
          }
        } else {
          this.loading = false;
          this.$message.error("请检查必填项!");
        }
      });
    },
    //删除箱子每一行
    onDelete(record, key) {
      this.dto.logisticsInfos.forEach((item, i) => {
        if (item.key === key) {
          this.dto.logisticsInfos.splice(i, 1);
        }
      });
    },
    //新增每一行SKU
    addSku(record) {
      let obj = {
        fnsku: null,
        productNumber: null,
        retreatLogisticsId: null,
        skuId: null,
        skuName: null,
      };
      obj.skuName = "请选择SKU";
      record.byRetreatProductInfos.push(obj);
      obj.key = Math.random();
      this.dto.logisticsInfos.forEach((item, index) => {
        if (record.key === item.key) {
          this.dto.logisticsInfos[index].byRetreatProductInfos =
            record.byRetreatProductInfos;
        }
      });
    },
    //新增箱子
    addBox() {
      let boxlist = {
        byRetreatProductInfos: [],
        caratNumber: null,
        highNumber: null,
        lengthNumber: null,
        logisticsId: null,
        logisticsName: null,
        packingNumber: null,
        retreatType: null,
        waybillNm: null,
        wideNumber: null,
      };
      boxlist.key = Math.random();
      let obj = {
        fnsku: null,
        productNumber: null,
        retreatLogisticsId: null,
        skuId: null,
        skuName: null,
      };
      obj.skuName = "请选择SKU";
      obj.key = this.dto.logisticsInfos.length;
      boxlist.byRetreatProductInfos.push(obj);
      this.dto.logisticsInfos.push(boxlist);
    },
    //删除每一行SKU
    delSku(record, item) {
      record.byRetreatProductInfos.forEach((v, i) => {
        if (v.key === item.key) {
          if (record.byRetreatProductInfos.length === 1) {
            this.$message.error("每个箱子最少存放一个SKU！");
            return false;
          }
          record.byRetreatProductInfos.splice(i, 1);
        }
      });
    },
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text
          .toLowerCase()
          .indexOf(input.toLowerCase()) >= 0
      );
    },
    showModal() {
      if (this.$refs.fromDto) {
        this.$refs.fromDto.resetFields();
      }
      this.inputShow = "";
      this.modalFlag = "add";
      this.visible = true;
      this.dto.logisticsInfos = [];
      this.dto.remark = null;
      this.dto.title = null;
      this.dto.typeId = null;
      this.dto.typeName = null;
      this.dto.warehousingId = null;
      this.dto.scheduledTime = null;
    },
    //获取下拉框选择值
    async getSelection() {
      let { code, responseBody } = await treeTagDictionary({
        tagType: 8,
      });
      if (code === "200") {
        this.treatmentArray = responseBody;
      }

      let res = await getRetreatStock();
      if (res.code === "200") {
        this.RetreatStockArray = res.responseBody;
      }
    },
    //获取库位
    async getStorageLocation() {
      let { code, responseBody } = await warehouse_select({
        warehousePid: this.dto.warehousingId,
        isTree: true,
      });
      if (code === "200") {
        this.storageLocation = this.getSkuTypeThree(responseBody);
      }
    },
    //封装组装后台数据
    getSkuTypeThree(data) {
      data.forEach((item) => {
        item.label = item.titleName;
        item.children = item.child;
        item.value = item.warehouseId;
        item.sort = this.sort;
        if (item.children && item.children.length >= 1) {
          this.sort += 1;
          this.getSkuTypeThree(item.children);
        }
      });
      this.sort = 0;
      return data;
    },
  },
};
</script>

<style lang="less" scoped>
.row-btn {
  font-size: 18px;
  i {
    margin: 0 5px;
    cursor: pointer;
  }
}
/deep/.ant-table-header-column {
  width: 100% !important;
}

.boxlist-tab {
  .boxlist-columns {
    display: flex;
    text-align: center;
    div {
      border: 1px solid #ccc;
      // width: 110px;
      // flex: 1;
    }
  }
}
.boxlist-pto {
  text-align: center;
  display: flex;
  padding: 0;
  li {
    // flex: 1;
    list-style: none;
    text-align: center;
    border: 1px solid #ccc;
  }
}

/deep/.blueBtn {
  background: #409cff;
  color: #fff !important;
  border: 1px solid #409cff !important;
}
.blueBtn:focus,
.blueBtn:hover {
  background: #409cff;
  color: #fff !important;
  border: 1px solid #409cff !important;
}
/deep/.columns-tab {
  width: 10% !important;
  .columns {
    display: flex;
    div {
      // width: 110px;
      text-align: center;
      border: 1px solid #ccc;
    }
  }
}
/deep/.columns-tabs {
  width: 10% !important;
  .columns {
    display: flex;
    div {
      // width: 110px;
      text-align: center;
      border: 1px solid #ccc;
    }
  }
}

.pto-list {
  display: flex;
  list-style: none;
  padding: 0;
  margin: 0;
  li {
    // width: 110px;
    // flex: 1;
    border: 1px solid #ccc;
    box-sizing: border-box;
    // padding: 3px 0;
    // height: 2rem;
  }
}
.pto-lists {
  display: flex;
  list-style: none;
  width: 100%;
  padding: 0;
  margin: 0;
  li {
    // width: 110px;
    flex: 1;
    border: 1px solid #ccc;
    box-sizing: border-box;
    // padding: 3px 0;
    // line-height: 2.7rem;
  }
}

/deep/.ant-modal-footer {
  text-align: center !important;
  button {
    margin: 0 50px;
  }
}
</style>
